<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Curl;
use app\common\lib\Status;
use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

class WorkRob
{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\WorkRob();
    }

    public function getListByWhere($where,$page,$limit,$field='*'){
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    public function getCountByWhere($where,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        $list = $this->model->getNormalListByWhere($where,$field);

        return count($list);
    }

    public function resetTextList($list){
        if (empty($list)){
            return [];
        }

        //零活
        $workBis = new Work();
        $workWhere = [
            ['id','in',array_column($list,'work_id')]
        ];
        $workList = $workBis->getListByWhere($workWhere,0,0,'id,department_id,name,longitude,latitude,address,start_time,price,valuation,show_time,process_status,user_id');
        if (!empty($workList)){$workList = $workBis->resetTextList($workList);}
        $workArr = Arr::getKeyValueByTwoArray($workList,'','id',2);
        foreach ($list as $k=>$v){
            $list[$k]['work'] = $workArr[$v['work_id']] ?? [];
        }
        return $list;
    }

    public function handleData($data)
    {
        if ($data['user_id'] == 0){
            throw new Exception("不存在该用户");
        }
        if ($data['work_id'] == 0){
            throw new Exception("不存在该零活");
        }

        $userBis = new User();
        $user = $userBis->getNormalUserById($data['user_id']);
        if (!$user) {
            throw new Exception("不存在该用户");
        }
        //必须实名认证，也能抢活
        $autherizedFlag = $userBis->checkIsAutherized($user['autherized']);
        if (!$autherizedFlag){
            throw new Exception("请先通过实名认证");
        }

        $userInfo = (new UserInfo())->getNormalSimpleInfoByField('user_id',$data['user_id']);
        if (empty($userInfo)){
            throw new Exception("不存在该用户");
        }
        if ($userInfo['education']==0||$userInfo['intention']==0||$userInfo['free']==0){
            throw new Exception("请先完善个人资料、技能标签后再抢活，可提高抢活成功率");
        }

        $work = (new Work())->getNormalById($data['work_id']);
        if (!$work) {
            throw new Exception("不存在该零活");
        }

        if ($work['user_id'] == $data['user_id']){
            throw new Exception("不可对自己发布的零活进行该操作");
        }

        if($work['is_show']!=1 || $work['process_status']!=1){
            //必须是公开且招工中的活才能抢
            throw new Exception("该零活状态暂不可抢");
        }

        //已抢过判断
        $where = $data;
        $workRob = $this->getNormalByWhere($where);
        if (!empty($workRob)){
            throw new Exception("已抢该零活，请勿重复操作");
        }

        $data['is_employed'] = 2;//暂未录用

        try {
            $res = $this->model->save($data);
        } catch (\Exception $e) {
            throw new Exception("数据库内部异常");
        }
        return $res;
    }

    public function getNormalByWhere($where,$field='*'): array
    {
        $data = $this->model->getNormalByWhere($where, $field);
        if (!$data) {
            return [];
        }
        return $data->toArray();
    }

    public function getNormalById($id)
    {
        $data = $this->model->getById($id);
        if (!$data) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * 判断是否抢活
     * @param $userId
     * @param $workId
     * @return array|\think\Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function isRob($userId,$workId){
        return $this->model->where(['user_id'=>$userId,'work_id'=>$workId])->find();
    }

    public function getJoinPageList($where,$page,$limit,$type,$spaceData = []){
        //$where[]=['work.status','=',config("status.mysql.table_normal")];
        $mapWork = [];
        if($type==1){
            //已申请 未雇佣
            $where[]=['is_employed','=',2];
        }else if($type==2){
            //雇佣自己且招工中未完工为待开工或已过期
            $where[]=['is_employed','=',1];
            $mapWork[]=['process_status','in',[1,4]];
        }else if($type==3){
            //雇佣自己且已完工
            $where[]=['is_employed','=',1];
            $mapWork[]=['process_status','=',2];
        }
        //is_employed = 1 && process_status = 3 取消的，不会存在，取消的不会有派遣
        $model=new \app\common\model\mysql\Work();
        $bField=implode(',',array_keys($model->schema));
        if (!empty($where)){
            foreach ($where as $k=>$v){
                $where[$k][0] = 'lm_work_rob.'.$v[0];
            }
        }
        $list=$this->model::hasWhere('work',$mapWork)->field(['workRob.id','workRob.user_id','workRob.work_id','workRob.is_employed','workRob.create_time','workRob.update_time'])->with(['work'=>function($query) use ($bField){
            $query->field($bField);
        }])->where($where)->page($page,$limit)->select();
        $list=$list->isEmpty()?[]:$list->toArray();
        $total=$this->model::hasWhere('work',$mapWork)->field(['workRob.id'])->with(['work'=>function($query) use ($bField){
            $query->field($bField);
        }])->where($where)->count();
        $workBis=new Work();
        foreach ($list as $k=>$v){
            $workList = $workBis->distanceCalc([$v['work']],$spaceData);
            $list[$k]['work']=$workBis->resetTextList($workList)[0];
        }
        return ['list'=>$list,'count'=>$total];
    }

    /**
     * 零活申请人列表
     * @param $page
     * @param $limit
     * @param $param
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getTableJoinList($page,$limit,$param=[]): array
    {
        $where=[];
        if(!empty($param['is_employed'])){
            $where[]=['is_employed','=',$param['is_employed']];
        }
        $where[]=['work_id','=',$param['work_id']];
        $userModel=new \app\common\model\mysql\User();
        $userInfoModel=new \app\common\model\mysql\UserInfo();
        $userSchema=array_keys($userModel->schema);
        $userInfoSchema=array_keys($userInfoModel->schema);
        $list=$this->model->field(['id','user_id','work_id','is_employed','create_time','update_time'])->with(['user'=>function($query) use ($userSchema){
            $query->field($userSchema);
        },'userInfo'=>function($query) use ($userInfoSchema){
            $query->field($userInfoSchema);
        }])->where($where)->page($page,$limit)->order('is_employed asc,create_time desc,id desc')->select();
        $list=$list->isEmpty()?[]:$list->toArray();
        $total=$this->model->field(['id'])->with(['user'=>function($query) use ($userSchema){
            $query->field($userSchema);
        },'userInfo'=>function($query) use ($userInfoSchema){
            $query->field($userInfoSchema);
        }])->where($where)->count();
        $userInfoBis=new UserInfo();
        $categoryDictionaries = (new Category)->categoryDictionaries();
        $workTypeDictionaries = (new WorkType)->categoryDictionaries();

        $commentBis = new Comments();
        foreach ($list as $k=>$v){
            $list[$k]['total_score'] = $commentBis->handlerCalcTotalScore(2,$v['user_id']);
            $list[$k]['userInfo']=$userInfoBis->resetUserInfo($v['userInfo'],$categoryDictionaries,$workTypeDictionaries);
        }
        return ['list'=>$list,'count'=>$total];
    }

    /**
     * 获取对应数量
     * @param array $param
     * @return int
     */
    public function getEmployedNum($param=[])
    {
        $where=[];
        if(!empty($param['is_employed'])){
            $where[]=['is_employed','=',$param['is_employed']];
        }
        $where[]=['work_id','=',$param['work_id']];
        $count=$this->model->where($where)->count();
        return $count;
    }

    /**
     * 录用人员
     * @param $ids
     * @param $work_id
     * @return bool
     */
    public function employed($ids,$work_id): bool
    {
        $ids=explode(',',$ids);
        if (empty($ids) || $work_id == 0){
            throw new Exception('参数错误');
        }

        //判断人数是否达到用工人数
        $workBis = new Work();
        $workInfo = $workBis->getNormalById($work_id);
        if (empty($workInfo)){
            throw new Exception('零活不存在');
        }
        if ($workInfo['process_status'] != 1){
            throw new Exception('只有招工中的零活才能派遣');
        }
        $mapRob = [
            ['work_id','=',$work_id],
            ['is_employed','=',1]
        ];
        $workRobList = $this->getListByWhere($mapRob,0,0);
        $trueWorkRobCount = count($workRobList);
        if ($trueWorkRobCount >= $workInfo['population']){
            throw new Exception('已派遣足够用工人数，无法再派遣');
        }

        if ($trueWorkRobCount < $workInfo['population']){
            $diff = $workInfo['population'] - $trueWorkRobCount;
            if (count($ids) > $diff){
                throw new Exception('当前只能再派遣 '.$diff.' 人（用工人数 '.$workInfo['population'].'，已派遣 '.$trueWorkRobCount.'）');
            }
        }

        return $this->model->where([['id','in',$ids]])->save(['is_employed'=>1]);
    }

    /**
     * 取消录用人员
     * @param $id
     * @return bool
     */
    public function employedCancel($id): bool
    {
        if ($id == 0){
            throw new Exception('参数错误');
        }

        $workRob = $this->getNormalById($id);
        if (empty($workRob)){
            throw new Exception('该记录不存在');
        }
        if ($workRob['is_employed'] != 1){
            throw new Exception('该记录不符合取消条件');
        }
        //判断零活状态是否可取消
        $workBis = new Work();
        $workInfo = $workBis->getNormalById($workRob['work_id']);
        if (empty($workInfo)){
            throw new Exception('零活不存在');
        }
        if ($workInfo['process_status'] == 2){
            throw new Exception('该零活已完工，不可取消派遣');
        }

        return $this->model->where([['id','=',$id]])->save(['is_employed'=>2]);
    }
}
